package com.kangfu.api.service.impl;

import com.kangfu.api.service.ITakeMedicineRecordService;
import com.kangfu.common.exception.BusinessException;
import com.kangfu.db.domain.entity.TakeMedicineRecord;
import com.kangfu.db.mapper.TakeMedicineRecordMapper;
import com.kangfu.db.model.request.TakeMedicineRequest;
import com.kangfu.db.model.vo.TakeMedicineInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class TakeMedicineRecordServiceImpl implements ITakeMedicineRecordService {

    @Autowired
    public TakeMedicineRecordMapper takeMedicineRecordMapper;


    @Override
    public List<TakeMedicineInfoVo> selectTakeMedicineListByDate(int userId, LocalDate remindDate) {

        List<TakeMedicineInfoVo> list = takeMedicineRecordMapper.selectTakeMedicineListByDate(userId, remindDate);

        return list;
    }

    @Override
    public int add(int userId, TakeMedicineRequest takeMedicineRequest) {

        List<LocalDateTime> remindTimeList = takeMedicineRequest.getRemindTimeList();
        if (remindTimeList == null || remindTimeList.isEmpty()) {
            throw new BusinessException("请选择提醒时间");
        }
        List<TakeMedicineRecord> takeMedicineRecordList = new ArrayList<TakeMedicineRecord>();
        for (LocalDateTime remindTime : remindTimeList) {
            TakeMedicineRecord takeMedicineRecord = new TakeMedicineRecord();
            takeMedicineRecord.setTitle(takeMedicineRequest.getTitle());
            takeMedicineRecord.setDescription(takeMedicineRequest.getDescription());
            takeMedicineRecord.setCreateTime(LocalDateTime.now());
            takeMedicineRecord.setRemindTime(remindTime);
            takeMedicineRecord.setUserId(userId);
            takeMedicineRecordList.add(takeMedicineRecord);
        }

        return takeMedicineRecordMapper.insertTakeMedicineRecord(takeMedicineRecordList);
    }

    @Override
    public void checkin(int userId, int id) {
        //查找用户的打卡提醒
        TakeMedicineRecord takeMedicineRecord = takeMedicineRecordMapper.selectTakeMedicineById(id, userId);
        if (takeMedicineRecord == null || 0 != takeMedicineRecord.getStatus()) {
            throw new BusinessException("您已打卡");
        }
        takeMedicineRecordMapper.updateTakeMedicineRecordStatus(id);
    }

    @Override
    public void del(int userId, int id) {
        //查找用户的打卡提醒
        TakeMedicineRecord takeMedicineRecord = takeMedicineRecordMapper.selectTakeMedicineById(id, userId);
        if (takeMedicineRecord == null || 0 != takeMedicineRecord.getStatus()) {
            throw new BusinessException("您已打卡，不能删除");
        }
        takeMedicineRecordMapper.deleteTakeMedicineRecord(id);
    }


}
